﻿<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head><link rel="stylesheet" href="${ctx}/common/common.css">
    <title>Title</title>
    <link rel="stylesheet" href="${ctx}/common/plugins/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctx}/common/plugins/layuiadmin/style/admin.css" media="all">
    <script src="${ctx}/common/plugins/layuiadmin/layui/layui.js"></script>
    
    <script src="${ctx}/common/plugins/publicJs/publicJs.js"></script>
	<style type="text/css">
    	.rowtop{
    		padding: 10px
    	}
    </style>
</head>
<body>
<form class="layui-form layui-container"  action="${ctx}/products/${action}">
    <input type="hidden" name="id" value="${entity.id}" />
    <input type="hidden" id="standardNum" value="${entity.standardNum}" />
    <div class="layui-row rowtop" style="margin-top: 20px;">
    	<div class="layui-col-md5">
	        <label class="layui-form-label">产品名称<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="name" maxlength="10" required value="${entity.name}"  lay-verify="required" placeholder="请输入产品名称" autocomplete="off" class="layui-input">
	        </div>
    	</div>
	    <div class="layui-col-md5">
	        <label class="layui-form-label">规格<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="specifications" lay-verify="required" value="${entity.specifications}" placeholder="请输入规格" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	    <%-- <div class="layui-col-md5">
			<label class="layui-form-label">产品类型</label>
			<div class="layui-input-block">
				<select name="t_p_id">
					<option value="">请选择问题</option>
					<c:forEach items="${proClassifyList}" var="p">
						<optgroup label="${p.name}">
							<c:forEach items="${p.childrenList}" var="pc">
								<option value="${pc.id}" <c:if test="${entity.t_p_id eq pc.id}">selected=selected</c:if>> ${pc.name}</option>
						    </c:forEach>
						</optgroup>
					</c:forEach>
				</select>
			</div>
		</div> --%>
		<div class="layui-form-item layui-col-md5">
	        <label class="layui-form-label">产品类型<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="hidden" name="tPId" id="t_p_id"  value="${entity.tPId}" class="layui-input">
	            <input readonly id="classilyName" lay-type="showPerson" value="${classifyEntity.name}" lay-verify="required" placeholder="请选择产品类别" autocomplete="off" class="layui-input">
	        </div>
   		</div>
	    <div class="layui-col-md5">
	        <label class="layui-form-label">产品编码<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="standardNum" lay-verify="isRepeat" value="${entity.standardNum}"  placeholder="请输入产品标识码" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	    <div class="layui-col-md5">
	        <label class="layui-form-label">保质期<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="shelfLife" lay-verify="required|number" value="${entity.shelfLife}"  placeholder="请输入保质期" autocomplete="off" class="layui-input">
	        </div>
	    </div>
	    <div class="layui-col-md5">
	    	<label class="layui-form-label">溯源类型<span style="color: red">*</span></label>
			<div class="layui-input-block">
				<select name="traceabilityType" lay-verify="required" lay-filter="aihao">
					<c:forEach items="${traceabilityCode}" var="tcode">
						<option value="${tcode.code}" <c:if test="${entity.traceabilityType eq tcode.code}">selected=selected</c:if> >${tcode.described}</option>
					</c:forEach>
				</select>
			</div>
		</div>
	</div>
	<div class="layui-row rowtop">
	     <div class="layui-col-md5">
	        <label class="layui-form-label">执行标准</label>
	        <div class="layui-input-block">
	            <input type="text" name="perfStandard" value="${entity.perfStandard}"  placeholder="请输入执行标准" autocomplete="off" class="layui-input">
	        </div>
	    </div>
	    <div class="layui-col-md5">
	        <label class="layui-form-label">投产时间<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="intoProductionTime" id="intoProductionTime" readonly lay-verify="required" value="<fmt:formatDate value='${entity.intoProductionTime}' pattern="yyyy-MM-dd HH:mm:ss"/>"  placeholder="请输入投产时间" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	    <div class="layui-col-md5">
	        <label class="layui-form-label">容量</label>
	        <div class="layui-input-block">
	            <input type="text" name="capacity" lay-verify="isNumber" value="${entity.capacity}"  placeholder="请输入容量" autocomplete="off" class="layui-input">
	        </div>
	    </div>
	    <div class="layui-col-md5">
	        <label class="layui-form-label">重量</label>
	        <div class="layui-input-block">
	            <input type="text" name="weight" lay-verify="isNumber" value="${entity.weight}"  placeholder="请输入重量" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	    <div class="layui-col-md5">
	        <label class="layui-form-label">工序数</label>
	        <div class="layui-input-block">
	            <input type="text" name="processNum" lay-verify="isNumber" value="${entity.processNum}"  placeholder="请输入工序数" autocomplete="off" class="layui-input">
	        </div>
	    </div>
	    <div class="layui-col-md5">
	        <label class="layui-form-label">商标号<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="trademarkNum" lay-verify="required" value="${entity.trademarkNum}"  placeholder="请输入商标号" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	     <div class=" layui-col-md5">
	        <label class="layui-form-label">参考单价</label>
	        <div class="layui-input-block">
	            <input type="text" name="referUnitPrice" lay-verify="isNumber" value="${entity.referUnitPrice}"  placeholder="请输入参考单价" autocomplete="off" class="layui-input">
	        </div>
	    </div>
	    <div class=" layui-col-md5">
	        <label class="layui-form-label">单位<span style="color: red">*</span></label>
	        <div class="layui-input-block">
	            <input type="text" name="unit" maxlength="3" lay-verify="required" value="${entity.unit}"  placeholder="请输入单位" autocomplete="off" class="layui-input">
	        </div>
	    </div>
    </div>
    <div class="layui-row rowtop">
	     <div>
	        <label class="layui-form-label">产品介绍</label>
			<div class="layui-input-block">
				<textarea name="introduction" placeholder="请输入产品介绍" class="layui-textarea">${entity.introduction}</textarea>
			</div>
	    </div>
    </div>
    <div class="layui-row rowtop">
		<div class="layui-form-item layui-upload">
		  <button type="button" class="layui-btn" id="test2">选择图片</button>
		  <button type="button" class="layui-btn" id="uploadSubmit">上传</button>  
		  <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
		    	预览图：
		    <div class="layui-upload-list" id="demo2">
		    <c:forEach items="${imgList}" var="img">
		    	<div id="delDiv">
		    		<img style="width: 100px;height: 100px;" src="${ctx}${img.pictureImgT}" class="layui-upload-img">
		    		<button type="button" id="delImg" class="layui-btn layui-btn-sm delImg" value="${img.id}">删除</button>
		    	</div>
		    </c:forEach>
		    </div>
		 </blockquote>
		</div>
	</div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="formBtn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            <button type="button" id="rollback" class="layui-btn layui-btn-primary">返回</button>
        </div>
    </div>
    <input type="hidden" id="imgId" name="imgId">
    <input type="hidden" id="tImgId" name="tImgId">
</form>

<script>
    //Demo
    layui.use(['form', 'layer'], function(){
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;

        //监听提交
        form.on('submit(formDemo)', function(data){
            console.log("layui表单提交回调被触发");
            console.log("表单数据:", data.field);
            console.log("表单action:", $("form").attr("action"));
            
            // 显示加载状态
            layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
            $("#formBtn").attr("disabled",true);
            
            // 手动提交表单
            var form = $("form")[0];
            console.log("开始手动提交表单");
            
            // 创建FormData对象
            var formData = new FormData(form);
            
            // 使用fetch API提交表单
            fetch(form.action, {
                method: 'POST',
                body: formData
            }).then(function(response) {
                console.log("表单提交响应:", response.status);
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error("HTTP状态错误: " + response.status);
                }
            }).then(function(result) {
                console.log("服务器响应结果:", result);
                if (result === "success") {
                    console.log("表单提交成功，准备刷新列表");
                    layer.msg("保存成功!", {icon: 1}, function(){
                        // 刷新父页面的列表数据
                        if (window.parent && window.parent.layui && window.parent.layui.table) {
                            // 在弹窗中，刷新父页面的表格
                            window.parent.layui.table.reload('productReload');
                            window.parent.layer.closeAll();
                        } else {
                            // 如果不在弹窗中，跳转到列表页
                            window.location.href = "${ctx}/products/list";
                        }
                    });
                } else {
                    console.error("服务器返回失败结果:", result);
                    layer.msg("保存失败，请重试", {icon: 2});
                    $("#formBtn").attr("disabled",false);
                }
            }).catch(function(error) {
                console.error("表单提交错误:", error);
                layer.msg("提交失败，请重试", {icon: 2});
                $("#formBtn").attr("disabled",false);
            }).finally(function() {
                layer.closeAll('loading');
            });
            
            return false; // 阻止layui的默认提交行为
        });
    });

    layui.use('laydate', function(){
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#intoProductionTime' //指定元素
            ,type: 'datetime'
			,format: 'yyyy-MM-dd HH:mm:ss'  // 明确指定包含秒的格式
    		,showSeconds: true  // 显示秒选择器
        });
    });
    
    layui.use(['upload','layer'], function(){
    	  var $ = layui.$;
    	  var upload = layui.upload;
    	  var layer = layui.layer;
    	  
    	//多图片上传
	   	  upload.render({
	   	    elem: '#test2'
	   	    ,url: '${ctx}/products/uploadFile'
	   	    ,multiple: true
	   	    ,auto:false
	   	    ,async:false
	   	    ,exts:'jpg|png'
	   	    ,bindAction: '#uploadSubmit'
	   	    ,before: function(obj){
	   	    	
	   	    },
		   	choose: function(obj) {
	             var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
	             obj.preview(function(index, file, result){
	            	 var div = $('#demo2').append('<div><img style="width: 100px;height: 100px;" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"><button type="button" class="layui-btn layui-btn-sm demo-delete">删除</button><input type="hidden" id="imgId_'+index+'" name="imgId"><input type="hidden" id="tImgId_'+index+'" name="tImgId"></div>')
	            	 div.find('.demo-delete').on('click', function() {
	                     delete files[index]; //删除对应的文件
	                     $(this).parent().remove();
	                 }); 
	             });
		   	}
	   	   ,done: function(res, index, upload){
   	    		$("#imgId_"+index).val(res.fileName);
   	    		$("#tImgId_"+index).val(res.thumbnails);
   	    	 	console.log($("#imgId_"+index).val());
	   	    	$(".demo-delete").each(function(){
	   	    	    $(this).remove();
	   	        });
	   	    	delete this.files[index];
	   	    }
	   	  });
	   	  
	   	  // 删除图片事件处理
	   	  $('.delImg').on("click",function(){
	   		var imgId = $(this).val();
	   		var obj = $(this);
	   		$.ajax({
                url: "${ctx}/products/deleteImg",
                data: {imgId:imgId},
                method: 'POST',
                async:false,
                success: function (data) {
                    $(obj).parent().remove();
                }
            });
	   	  });
    });
    
    layui.use(['form', 'layer'], function(){
    	var $ = layui.$;
    	var form = layui.form;
    	var layer = layui.layer;
    	 form.verify({
             isRepeat: function(value, item){ //value：表单的值、item：表单的DOM对象
                 if(value.trim().length<=0){
                     return "必填项不能为空";
                 }
                 
                 // 获取原始值进行比较（编辑模式）
                 var originalValue = $("#standardNum").val();
                 if(originalValue && originalValue.trim() == value.trim()){
                     return; // 编辑模式且值没有变化，跳过验证
                 }
                 
                 var isSubmit = true;
                 var errorMsg = "";
                 
                 try {
                     $.ajax({
                         url: "${ctx}/products/checkStandardNum",
                         data: {standardNum:value},
                         method: 'POST',
                         async: false, // 保持同步以确保验证顺序
                         timeout: 3000, // 减少超时时间到3秒
                         success: function (data) {
                             if (data == '0') {
                                 isSubmit = false;
                                 errorMsg = "产品标识码已存在";
                             }
                         },
                         error: function(xhr, status, error) {
                             console.error("验证产品标识码时发生错误:", error);
                             isSubmit = false;
                             errorMsg = "验证失败，请稍后重试";
                         }
                     });
                 } catch(e) {
                     console.error("验证过程中发生异常:", e);
                     isSubmit = false;
                     errorMsg = "验证失败，请稍后重试";
                 }
                 
                 if(!isSubmit){
                     return errorMsg;
                 }
             },
             isNumber:function(value, item){
            	 var reg = /^\d+(?=\.{0,1}\d+$|$)/
            	 if(value.trim().length>0){
            		 if (!reg.test(value)) {
            			 return "只能填写数字";
            		 }
                 }
             }
         });
         
         // 分类选择功能
         document.getElementById("classilyName").addEventListener("click", function () {
             layer.open({
                 type: 2,
                 skin: 'layui-layer-rim', //加上边框
                 area: ['30%', '80%'], //宽高
                 content: '${ctx}/products/queryProCla'
             });
             form.render();
         });
         
    });
    
    document.getElementById("rollback").addEventListener("click",function(){
        window.history.back();
    });
    
    // 添加全局错误处理
    window.addEventListener('error', function(e) {
        console.error('JavaScript错误:', e.error);
    });
    
    // 添加表单提交前的调试信息
    layui.use(['jquery'], function(){
        var $ = layui.$;
        console.log("页面加载完成");
        console.log("jQuery版本:", $.fn.jquery);
        console.log("表单action属性:", $("form").attr("action"));
        console.log("当前action变量:", "${action}");
        
        // 监听表单提交事件
        $("form").on("submit", function(e) {
            console.log("原生表单提交事件被触发");
            console.log("表单action:", $(this).attr("action"));
        });
        
        // 测试jQuery是否正常工作
        console.log("表单元素数量:", $("form").length);
    });
</script>
</body>
</html>



